import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_block.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:photo_view/photo_view.dart";
import "package:photo_view/photo_view_gallery.dart";

class BillDetail extends StatefulWidget {
  final Map info;
  const BillDetail({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _BillDetailState();

}

class _BillDetailState extends State<BillDetail> {

  late ImagePicker _imagePicker;
  List<XFile>? _imageFile;

  Future<void> _pickImage() async {
    final pickedImage = await _imagePicker.pickMultiImage();
    if (pickedImage != null && pickedImage.length > 3) {
      pickedImage.removeRange(3, pickedImage.length);
    }
    if (pickedImage != null && pickedImage.isNotEmpty) {
      setState(() {
        _imageFile = pickedImage;
      });
    }
  }

  void _openImagePreview(List<String> images, int initialIndex) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          body: Stack(
            children: [
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child: PhotoViewGallery.builder(
                  scrollPhysics: const BouncingScrollPhysics(),
                  builder: (BuildContext context, int index) {
                    return PhotoViewGalleryPageOptions(
                      imageProvider: NetworkImage(images[index]),
                      initialScale: PhotoViewComputedScale.contained,
                      minScale: PhotoViewComputedScale.contained,
                      maxScale: PhotoViewComputedScale.covered * 2,
                    );
                  },
                  itemCount: images.length,
                  pageController: PageController(initialPage: initialIndex),
                  backgroundDecoration: const BoxDecoration(
                    color: Colors.black,
                  ),
                ),
              ),
              Positioned(
                top: 40,
                right: 20,
                child: IconButton(
                  icon: const Icon(Icons.close, color: Colors.white),
                  onPressed: () => Navigator.pop(context),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _renderPics() {
    if (widget.info["picUrl"] == null || widget.info["picUrl"].isEmpty) {
      return const SizedBox.shrink();
    }

    final List<String> images = widget.info["picUrl"].toString().split(",")
        .where((url) => url.isNotEmpty)
        .toList();
        
    if (images.isEmpty) {
      return const SizedBox.shrink();
    }

    return Wrap(
      spacing: 10,
      runSpacing: 10,
      children: [
        ...images.asMap().entries.map((entry) => GestureDetector(
          onTap: () => _openImagePreview(images, entry.key),
          child: Image.network(
            entry.value,
            width: 100,
            height: 100,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return Container(
                width: 100,
                height: 100,
                color: ThemeVars.colorBackground,
                child: const Icon(Icons.broken_image),
              );
            },
          ),
        )),
      ],
    );
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "账单详情",
      child: ListView(
        children: [
          Container(
            height: 100,
            alignment: Alignment.center,
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: Text("+${Utils.formatCurrency(widget.info["money"])}", style: TextStyle(fontSize: 20, color: ThemeVars.colorSuccess, fontWeight: FontWeight.w500),),
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            title: const Text("账单信息", style: TextStyle(fontWeight: FontWeight.w500),),
            items: [
              MenuBlockItem(
                text: "费用名称",
                showArrow: false,
                suffix: Text(widget.info["name"]),
              ),
              MenuBlockItem(
                text: "账单周期",
                showArrow: false,
                suffix: Text("${DateTools.formatYMD(widget.info["billCycleBegin"])} - ${DateTools.formatYMD(widget.info["billCycleEnd"])}"),
              ),
              MenuBlockItem(
                text: "支付时间",
                showArrow: false,
                suffix: Text(DateTools.formatYMD(widget.info["payTime"])),
              ),
              MenuBlockItem(
                text: "支付渠道",
                showArrow: false,
                suffix: Text(widget.info["payPlatForm"] == "2" ? "线下" : "线上"),
              ),
              MenuBlockItem(
                text: "操作人",
                showArrow: false,
                suffix: Text(widget.info["receiverName"]),
              ),
            ]
          ),
          const SizedBox(height: 12,),
          MenuBlock(
              title: const Text("租客信息", style: TextStyle(fontWeight: FontWeight.w500),),
              items: [
                MenuBlockItem(
                  text: "租客姓名",
                  showArrow: false,
                  suffix: Text(widget.info["renterName"] ?? "") ,
                ),
                MenuBlockItem(
                  text: "房源地址",
                  showArrow: false,
                  suffix: Text("${widget.info["room"]["buildingName"]}${widget.info["room"]["name"]}"),
                ),
              ]
          ),
          if (widget.info["remark"] != null) ...[
            const SizedBox(height: 12,),
            MenuBlock(
            items: [
              MenuBlockItem(
                text: "账单备注",
                showArrow: false,
                suffix: GestureDetector(
                  child: Text("编辑", style: TextStyle(color: ThemeVars.colorPrimary),),
                  onTap: () {
                    Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                      return EditRemark(remark: widget.info["remark"]);
                    },),).then((value) async {
                      if (value != null) {
                        Map<String, dynamic> params = {
                          "billId": widget.info["billId"],
                          "remark": value,
                        };
                        await billApi.updateBill(params);
                        EasyLoading.showSuccess("编辑成功");
                        setState(() {
                          widget.info["remark"] = value;
                        });
                      }
                    });
                  },
                ),
                tip: Utils.isNotEmpty(widget.info["remark"]) ? Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  margin: const EdgeInsets.only(top: 8),
                  width: double.maxFinite,
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(3)),
                    color: ThemeVars.colorBackground,
                  ),
                  child: Text(widget.info["remark"] ?? "", textAlign: TextAlign.left, style: const TextStyle(fontSize: 14),),
                ) : null,
              ),
            ]
          )],
          const SizedBox(height: 12,),
          MenuBlock(
            items: [
              MenuBlockItem(
                text: "凭证图片",
                showArrow: false,
                tip: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 8,),
                    _renderPics(),
                  ],
                ),
              ),
            ]
          ),
        ],
      ),
    );
  }

}